#pragma once
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <iostream>
#include <arpa/inet.h>
#include <cstdio>
#include <cstring>

class UdpClient
{
public: 
    UdpClient(uint16_t port , const std::string& ip) : _port(port), _svr_ip(ip){}
    ~UdpClient(){ close(_sock); }

    void init()
    {
         _sock = socket(AF_INET,SOCK_DGRAM,0); 
        if(_sock < 0)
        {
            std::cout << "create socket failed...." << std::endl;
            abort();
        }   
        svr.sin_port = htons(_port); 
        svr.sin_addr.s_addr = inet_addr(_svr_ip.c_str()); 
        svr.sin_family = AF_INET;

    }
    void start()
    {
        int i = 1; 
        char buff[1024] = {0};
        while(1)
        {
            std::cout << "Entry # ";
            fgets(buff,sizeof buff -1 , stdin); 
            buff[strlen(buff) - 1] = 0;
            std::string message = buff;   
            sendto(_sock,message.c_str(),message.size(),0,(struct sockaddr*)&svr,sizeof svr);
        }
    }

private: 
    int _sock;
    uint16_t _port;
    std::string _svr_ip;  
    struct sockaddr_in svr;

};